
const jwt = require('jsonwebtoken')

const writeList = [
  '/api/login',
  '/api/register',
  '/api/findGoods',
  '/api/updateGoods'
]

module.exports = () => {
  return async (ctx, next) => {
    if (!writeList.includes(ctx.path)) {
      const { authorization } = ctx.request.headers;
      try{
        const data = jwt.verify(authorization, ctx.app.config.keys)
        // 这个就是 存储用户信息的一个载体
        ctx.state = data;
        await next()
      } catch(err) {
        ctx.body = {
          code: -1,
          msg: 'token验证失败',
          err
        }
      }
    } else {
      await next()
    }
  }
}
